<?php /** @noinspection PhpUnused */

/**
 * Created by PhpStorm.
 * User: qch
 * Date: 2015/6/3
 * Time: 10:06
 */

namespace Aoe\Util;


/**
 * # 验证类
 */
class Validator
{
    /**
     * Validate that an attribute is a valid e-mail address.
     *
     * @param $value
     *
     * @return bool
     */
    public static function validateEmail($value): bool
    {
        return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
    }
    
    /**
     * Validate that an attribute is a valid URL.
     *
     * @param       $value
     *
     * @return bool
     */
    public static function validateUrl($value): bool
    {
        return filter_var($value, FILTER_VALIDATE_URL) !== false;
    }

    public static function validateMax($value, int $max = PHP_INT_MAX): bool
    {
        $v   = is_string($value) ? strlen($value) : (is_int($value) ? $value : 0);
        return $v <= $max;
    }

    public static function validateMin($value, int $min = PHP_INT_MIN): bool
    {
        $v   = is_string($value) ? strlen($value) : (is_int($value) ? $value : 0);
        return $v >= $min;
    }

    public static function validateLen($value, int $len): bool
    {
        return is_string($value) && strlen($value) === $len;
    }

    /**
     * Validate that an attribute contains only alphabetic characters.
     *
     * @param $value
     *
     * @return bool
     */
    protected static function validateAlpha($value): bool
    {
        return preg_match('/^[\pL\pM]+$/u', $value);
    }
    
    /**
     * Validate that an attribute contains only alphanumeric characters.
     *
     * @param $value
     *
     * @return bool
     * @internal param array $attribute
     */
    public static function validateAlphaNum($value): bool
    {
        return preg_match('/^[\pL\pM\pN]+$/u', $value);
    }
    
    /**
     * Validate that an attribute contains only alphanumeric characters, dashes, and underscores.
     *
     * @param $value
     *
     * @return bool
     * @internal param array $attribute
     */
    public static function validateAlphaDash($value): bool
    {
        return preg_match('/^[\pL\pM\pN_-]+$/u', $value);
    }
    
    /**
     * Validate that an attribute passes a regular expression check.
     *
     * @param string $patten
     * @param        $value
     *
     * @return bool
     */
    public static function validateRegex($value, string $patten): bool
    {
        return preg_match($patten, $value);
    }
    
    /**
     * Validate that an attribute matches a date format.
     *
     * @param array|string $attribute
     * @param              $value
     *
     * @return bool
     */
    public static function validateDateFormat($value, array | string $attribute = []): bool
    {
        $parsed = date_parse_from_format($attribute, $value);
        
        return ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0);
    }
}
